package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignClient;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoEntity;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    public final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());
        //已添加的商品改变数量
        if (StringUtils.hasLength(res)) {
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }

        CartItem cartItem = new CartItem();

        CompletableFuture<Void> getCartItemDetail = CompletableFuture.runAsync(() -> {
            //远程查询商品详情
            R r = productFeignClient.info(skuId);
            if (r.getCode() == 0) {
                SkuInfoEntity skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoEntity>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setPrice(skuInfo.getPrice());
                cartItem.setSkuId(skuId);
                cartItem.setTitle(skuInfo.getSkuTitle());
            }
        }, threadPoolExecutor);

        CompletableFuture<Void> getSkuSaleAttr = CompletableFuture.runAsync(() -> {
            List<String> skuSaleAttrString = productFeignClient.getSkuSaleAttrString(skuId);
            cartItem.setSkuAttr(skuSaleAttrString);
        }, threadPoolExecutor);

        CompletableFuture.allOf(getCartItemDetail, getSkuSaleAttr).join();
        cartOps.put(String.valueOf(skuId), JSON.toJSONString(cartItem));
        return cartItem;
    }

    @Override
    public CartItem getCartItemBySkuId(Long skuId) {
        BoundHashOperations cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.hasLength(res)) {
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            return cartItem;
        }
        return null;
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        if (userInfoTo.getUserId() != null) {
            //没登录的购物车
            List<CartItem> tempCartItems = getCartItems(userInfoTo.getUserKey());
            //登录和没登录的购物车需要合并
            List<CartItem> loginCartItems = getCartItems(userInfoTo.getUserId().toString());
            if (tempCartItems != null) {
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
                //清空购物车
                clearCart(userInfoTo.getUserKey());
            }
            //合并后的购物车
            List<CartItem> cartItems = getCartItems(userInfoTo.getUserId().toString());
            cart.setItems(cartItems);
        } else {
            //没登录的购物车
            List<CartItem> cartItems = getCartItems(userInfoTo.getUserKey());
            cart.setItems(cartItems);
        }

        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(CART_PREFIX + cartKey);
    }

    @Override
    public void check(Long skuId, Integer check) {
        BoundHashOperations cartOps = getCartOps();
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        BoundHashOperations cartOps = getCartOps();
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCount(num);
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCheckItem() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = userInfoTo.getUserId().toString();
            List<CartItem> cartItems = getCartItems(cartKey);
            if (cartItems != null && cartItems.size() > 0) {
                List<CartItem> collect = cartItems.stream().filter(e -> e.getCheck()).
                        map(e -> {
                            e.setPrice(productFeignClient.getPrice(e.getSkuId()));
                            return e;
                        }).collect(Collectors.toList());
                return collect;
            }
        }
        return null;
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations boundHashOps = redisTemplate.boundHashOps(CART_PREFIX + cartKey);
        List<String> values = boundHashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(e -> {
                CartItem cartItem = JSON.parseObject(e, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }


    private BoundHashOperations getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }


}
